package com.eastfair.file.controller;


import cn.hutool.core.util.StrUtil;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.file.service.FileService;
import com.eastfair.file.vo.FileVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 文件上传控制层
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class FileController {

    @Resource
    FileService fileService;

    /**
     * 本地文件上传
     *
     * @param file       the file
     * @param bucketName the bucket name
     * @param isMobile   the is mobile
     * @return r r
     * @throws Exception the exception
     */
    @PostMapping("/local-put-file")
    public R<FileVO> localPutFile(@RequestPart("file") MultipartFile file,
                                  @RequestParam("bucketName") String bucketName,
                                  @RequestHeader(value = "isMobile", required = false) String isMobile) throws Exception {
        log.info("localPutFile - 文件上传, bucketName={}", bucketName);
        ContextUtil.set("isMobile", isMobile);
        if (file == null || StrUtil.isEmpty(bucketName)) {
            return R.fail("参数不能为空");
        }
        return R.success(fileService.uploadFile(file, bucketName, isMobile));
    }

    /**
     * 本地文件上传
     *
     * @param file       the file
     * @param bucketName the bucket name
     * @param isVerify   the is mobile
     * @return r r
     * @throws Exception the exception
     */
    @PostMapping(value = "/uploadfile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<FileVO> serviceUploadFile(@RequestPart("file") MultipartFile file,
                                       @RequestParam("bucketName") String bucketName,
                                       @RequestHeader(value = "isMobile", required = false) String isVerify
    ) throws Exception {
        log.info("serviceUploadFile - 文件上传, bucketName={}", bucketName);
        if (file == null || StrUtil.isEmpty(bucketName)) {
            return R.fail("参数不能为空");
        }
        return R.success(fileService.uploadFile(file, bucketName, isVerify));
    }

}
